<template>
  <div style="padding: 2px 20px;background-color: #fff;width: 99%;margin: 5px auto 0px">
    <DynamicForm :labelWidth="85" style="margin-top: 20px;" :searchLoading="loading" :items="items" v-model="formModel" @onFinish="submit">
    </DynamicForm>
    <div style="margin-top: 5px;">
      <ElTableWithColumns
        @onChange="onChange"
        :loading="loading"
        :data="tableData"
        :columns="columns"
        :pagerInfo="pagerInfo"
        :operateColProps="{ width: 255 }"
      >
        <template #tableHeader>
          <MultifunctionalModal @onFinish="onFinish" :action="action" ref="updateModal" :title="title">
            <template #trigger="data">
              <el-button type="primary"  v-hasPermi="['payment:task:add']" @click="onTriggerClick(data)">创建项目</el-button>
            </template>
          </MultifunctionalModal>
        </template>
        <template #operate="{row}">
          <div>
            <el-tag type="primary" style="cursor: pointer;"   v-hasPermi="['payment:task:detail']"  @click="viewDetail(row as TaskInfo)" >详情 </el-tag>
            <el-tag type="primary" style="cursor: pointer;margin-left:2px;"  v-hasPermi="['payment:task:edit']"  v-if="row.taskStatus ==0 || row.taskStatus ==3 || row.taskStatus ==5"   @click="edit(row as TaskInfo)">编辑</el-tag>
            <el-tag type="success" style="cursor: pointer;margin-left:2px;"  v-hasPermi="['payment:task:publish']"   v-if="row.taskStatus ==0 || row.taskStatus ==3 || row.taskStatus ==5"   @click="publish(row as TaskInfo)">发布上线</el-tag>
            <el-popconfirm title="确定下架该项目吗?"   @confirm="upOrDown(row)" v-if="row.status == 1">
              <template #reference>
                <el-tag type="danger" style="cursor: pointer;margin-left:2px;" v-hasPermi="['payment:task:down']" >下架</el-tag>
              </template>
            </el-popconfirm>

            <el-tag type="success" style="cursor: pointer;margin-left:2px;" v-hasPermi="['payment:task:up']" v-else @click="upOrDown(row)">上架</el-tag>
            <!--
            <el-button type="primary" plain size="small" @click="viewDetail(row as TaskInfo)">详情</el-button>
            <el-button type="success" plain size="small" @click="edit(row as TaskInfo)">编辑</el-button>
            <el-button type="success" plain size="small" @click="publish(row as TaskInfo)">发布上线</el-button>
            <el-popconfirm title="确定下架该项目吗?" @confirm="upOrDown(row)">
              <template #reference>
                <el-button size="small" plain type="danger">下架</el-button>
              </template>
            </el-popconfirm>-->
          </div>
        </template>
      </ElTableWithColumns>
    </div>
    <Detail  :openCheck="openDetailCheck" @dialogClose="dialogClose2" :item="item"></Detail>

  </div>
</template>

<script lang="ts" setup>
import DynamicForm from '@/components/DynamicForm/index.vue';
import { getTaskList } from '@/api/projectMgt/index';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import MultifunctionalModal from '@/views/project/SharedComponents/MultifunctionalModal.vue';
import { ActionEnum, type TaskInfo } from '../types'
import Detail from "@/views/project/proSel/detail/index.vue"
import useUserStore from '@/store/modules/user'


import useDictUtilsStore from '@/store/modules/dict_utils'

const pagerInfo = reactive({
  pageSize: 10,
  total: 0,
  pageNum: 1
})

const action = ref<ActionEnum>(ActionEnum.PROJECT_ADD)

const title = ref<string>('创建项目')

const { getlabel, mapVOS } = useDictUtilsStore()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const openDetailCheck = ref(false);
/**
 * 业务类型
*/
const businessTypeOptions = computed(() => {
  const list = proxy?.useDict("wxfe_bus_type").wxfe_bus_type
  return list
})


const dialogClose2  = (params:any)=>{
    openDetailCheck.value = false;
}



/**
 * 接单类型
*/
const taskTypeOptions = computed(() => {
  const list = proxy?.useDict("task_type").task_type
  return list
})

/**
 * 项目状态
*/
// const taskStatusOptions = proxy?.useDict("task_status").task_status
const taskStatusOptions =computed(() => {
  const list = proxy?.useDict("task_status").task_status
  return list
})


/**
 * 上下架
*/
const proStatusoptions = proxy?.useDict("pro_status").pro_status


const router = useRouter()
const loading = ref(false)

const updateModal = ref<{ onEdit?: (data: TaskInfo) => void }>()

const onTriggerClick = (payload: {setVisible: (open: boolean) => void }) => {
  payload.setVisible(true)
  action.value = ActionEnum.PROJECT_ADD
}

const edit = (row: TaskInfo) => {
  updateModal?.value?.onEdit!(row)
  action.value = ActionEnum.PROJECT_EDIT
  title.value = '编辑项目'
}


const tableData = ref<TaskInfo[]>([])

const viewDetail = (row: TaskInfo) => {
  openDetailCheck.value = true;
  item.value = row;
  // router.push (`/project/projectDetail?id=${row.id}`)
}

const publish = (data: TaskInfo) => {
  loading.value = true
  useRequest('/payment/task/edit', 'PUT', {
    data: {
      ...data,
       taskStatus: 1
     }
  }, {
    immediate: true,
    onFinish: () => {
      loading.value = false
    },
    onSuccess: () => {
      ElMessage.success('操作成功')
      query()
    }
   })
}

const upOrDown = (data: TaskInfo) => {
  loading.value = true
  useRequest('/payment/task/ups', 'put', {
    data: {
      status: data?.status === 1 ? 2 : 1,
      id: data.id,
      merId: data?.merId
     }
  }, {
    immediate: true,
    onFinish: () => {
      loading.value = false
    },
    onSuccess: () => {
      ElMessage.success('操作成功')
      query()
    }
   })
}


const columns = [
  {
    title: '创建时间',
    dataIndex: 'addTime',
    width: 160
  },
  {
    title: '企业名称',
    dataIndex: 'merchantName',
    width: 200
  },
  {
    title: '服务商名称',
    dataIndex: 'gsmc',
    width: 200
  },
  {
    title: '项目编号',
    dataIndex: 'no',
    width: 140
  },
  {
    title: '项目标题',
    dataIndex: 'name',
    width: 190
  },
  {
    title: '服务金额（元）',
    dataIndex: 'taskCode',
    renderText: (row: TaskInfo) => {
      const {costMax,classify} = row
      if(classify == 1){
        return proxy?.convertFenToYuan(row.cost) +" ~ "+ proxy?.convertFenToYuan(row.costMax);
      }else{
        return `${proxy?.convertFenToYuan(row.cost)}`
      }
    },
    width: 180
  },
  {
    title: '接单类型',
    dataIndex: 'classify',
    width: 100,
    renderText: row => {
         return getlabel('task_type', row.classify)
    }
  },
  {
    title: '项目状态',
    dataIndex: 'taskStatus',
    width: 120,
    renderText: row => {
         return getlabel('task_status', row.taskStatus)
    }

  },
  {
    title: '业务类型',
    dataIndex: 'busType',
    width: 120,
    renderText: row => {
         return getlabel('wxfe_bus_type', row.busType)
    }
  },

  {
    title: '上架状态',
    dataIndex: 'status',
    width: 100,
    renderText: row => {
         return getlabel('pro_status', row.status)
    }
  },
]


const formModel = ref({})
const item = ref({})


const items = computed(() => {
  return [
    { prop: 'addTime1', label: '创建时间', valueType: 'date', fieldProps: { type: 'daterange', valueFormat: 'YYYY-MM-DD','start-placeholder':"开始日期",'end-placeholder':"结束日期" } },
    { prop: 'no', label: '项目编号', valueType: 'input'  , fieldProps: {placeholder:"请输入项目编号"}},
    { prop: 'name', label: '项目标题', valueType: 'input' , fieldProps: {placeholder:"请输入项目标题"}},
    { prop: 'taskStatus', label: '项目状态', valueType: 'select', options: taskStatusOptions.value , fieldProps: {placeholder:"请选择项目状态"}},
    { prop: 'classify', label: '接单类型', valueType: 'select', options: taskTypeOptions?.value , fieldProps: {placeholder:"请选择接单类型"}},
    { prop: 'busType', label: '业务类型', valueType: 'select', options: businessTypeOptions.value, fieldProps: {placeholder:"请选择业务类型"} },
  ]
})



const query = async (formData = {}) => {
  loading.value = true

  const { total, ...submitData } = {
    ...formData,
    ...pagerInfo
  }

  if( formData.addTime1 && formData.addTime1.length > 1 ){
      submitData.beginDate = formData.addTime1[0];
      submitData.endDate = formData.addTime1[1];
  }


  let defaultProvider = useUserStore().defaultProvider;


  submitData.sydId = defaultProvider.sydId;

  const [err, res] = await to(getTaskList(submitData))

  loading.value = false
  if (err) {
    ElMessage.error('获取列表失败')
  } else {
    const { code } = res
    if (code === HttpStatus.SUCCESS) {
      tableData.value = res?.rows
      pagerInfo.total = res.total
    }
  }
}

const onFinish = (response) => {
  if (response.value.code === 200) {
    ElMessage.success('操作成功')
    query()
  }
}


const onChange = ({data, type}) => {
  if (type === 'pageNo') {
    pagerInfo.pageNum = data
  }
  if (type === 'pageSize') {
    pagerInfo.pageSize = data
  }
  query()
}

const submit = data => {
  query(data)
}

onMounted(() => {
  query()
})
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
